package com.powernode.money.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.powernode.money.constant.Constants;
import com.powernode.money.mapper.LoanInfoMapper;
import com.powernode.money.model.LoanInfo;
import com.powernode.money.service.LoanInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Service(interfaceClass = LoanInfoService.class, version = "1.0.0", timeout = 15000)
public class LoanInfoServiceImpl implements LoanInfoService {

    @Autowired
    private LoanInfoMapper loanInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public double queryHistoryAverageRate() {
        Double rate = (Double) redisTemplate.opsForValue().get(Constants.HISTORY_AVERAGE_RATE);
        if (rate == null) {
            synchronized (this) {
                rate = (Double) redisTemplate.opsForValue().get(Constants.HISTORY_AVERAGE_RATE);
                if (rate == null) {
                    rate = loanInfoMapper.selectHistoryAverageRate();
                    redisTemplate.opsForValue().set(Constants.HISTORY_AVERAGE_RATE, rate, 30, TimeUnit.MINUTES);

                }
            }
        }
        return rate;
    }

    @Override
    public LoanInfo queryByPrimaryKey(Integer id) {
        return loanInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<LoanInfo> queryByProductTypeWithPage(int ptype, int pageNum, int pageSize) {
        return loanInfoMapper.selectByProductTypeWithPage(ptype, pageNum, pageSize);
    }

    @Override
    public int executeUpdateByPrimaryKeySelective(LoanInfo record) {
        return loanInfoMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int queryRowsByPtype(int ptype) {
        return loanInfoMapper.selectRowsByPtype(ptype);
    }
}
